'use client';

import Avatar from '@/asset/avatar.png';
import { useToast } from '@/hooks/use-toast';
import { authClient } from '@/lib/auth-client';
import { genUserAvatarKey } from '@/lib/cos';
import { useCosClient } from '@/providers/cos-provider';
import Image from 'next/image';
import { Button } from '../ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import ImagePreview from './image-preview';
import ImageUploader from './image-uploader';
import QueryImage from './query-image';

export default function UserAvatar() {
  const { data: session } = authClient.useSession();
  const { toast } = useToast();
  const cosClient = useCosClient();

  const updateUserImage = async (key: string) => {
    const preKey = session?.user.image;
    const { error } = await authClient.updateUser({ image: key });
    error
      ? toast({ title: error.message, variant: 'destructive' })
      : toast({ title: '上传成功' });
    !error && preKey && cosClient?.delete([preKey]);
  };

  return (
    <Popover>
      <PopoverTrigger>
        <QueryImage
          imageKey={session?.user.image ?? undefined}
          defaultImage={Avatar}
          wrapperClassName="w-24 h-24 rounded-full"
          imgClassName="rounded-full w-full h-full object-cover"
        />
      </PopoverTrigger>
      <PopoverContent className="flex gap-2 p-1 w-fit">
        {session?.user.image && (
          <ImagePreview
            imageKey={session.user.image}
            button={<Button variant="ghost">查看</Button>}
          />
        )}
        {session?.user.id && (
          <ImageUploader
            single
            button={<Button variant="ghost">上传</Button>}
            onUploaded={(keys) => updateUserImage(keys[0])}
            genImageKey={() => genUserAvatarKey(session.user.id)}
          />
        )}
      </PopoverContent>
    </Popover>
  );
}
